﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gollie.DataTables;
using Gollie.Mail;

namespace Gollie.Controls.Admin
{
	public partial class ActivateVendor : AdminRequiredBaseUserControl
	{
		InactiveVendors inactiveVendors;
	
		protected override void OnFirstHit(object sender, EventArgs e)
		{
			this.Populate();
		}

		private void Populate()
		{
			inactiveVendors = new InactiveVendors();

			this.GridView1.DataSource = inactiveVendors;

			this.GridView1.DataBind();
		}

		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if (e.CommandName == "Activate")
			{
				inactiveVendors = new InactiveVendors();

				int index = Convert.ToInt32(e.CommandArgument);

				ulong contactPersoonId = inactiveVendors[index].ContactPersoonId;
				ulong bedrijfsId = inactiveVendors[index].BedrijfsId;

				string adminPassword = Hash.GetRandomPassword();
				string hashed = Hash.GetHash(adminPassword);

				DropDownList ddlBranche = this.GridView1.Rows[index].FindControl("ddlBranche") as DropDownList;
				int brancheId = Convert.ToInt32(ddlBranche.SelectedValue);

				Database.Queries.ActivateVendor(contactPersoonId, hashed, bedrijfsId, brancheId);

				this.SendMail(index, adminPassword);

				this.Populate();
			}

		}

		private void SendMail(int index, string password)
		{
			string userName = inactiveVendors[index].UserName;

			UserInfo admin = UserInfo.GetUserInfo(userName, false);

			MailClient.Queue(new EMail
				{
					Name = "vendoractivated",
					Recipients = admin.Email,
					Args = new Dictionary<string, string>()
					{
												{ "{businessname}", inactiveVendors[index].Bedrijfsnaam },
												{ "{aanhef}", admin.MailAanhef },
												{ "{password}", password },
												{ "{dealspage}", ConfigAppSettings.GetValue("VendorDealsUrl") + "?v=" + admin.VendorId.ToString() }
										    
					}
				}
			);
		}

		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				Control c = e.Row.FindControl("ddlBranche");
				if (c != null)
				{
					DropDownList ddlBranche = c as DropDownList;
					var branches = VendorBranche.GetInstance().Branches;
					foreach (KeyValuePair<int, BrancheInfo> branche in branches)
					{
						ddlBranche.Items.Add(new ListItem(branche.Value.Name, branche.Value.Id.ToString()));
					}
				}
			}

		}
	}
}